import "dart:convert";
import "dart:async";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/transfer_station.dart";
import "package:ct_pa_majordomo/pages/user/api.dart";
import "package:ct_pa_majordomo/pages/user/create_apartment/apartment_form/index.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/utils/index.dart";

class CreateApartment extends StatefulWidget {
  const CreateApartment({super.key});

  @override
  State<StatefulWidget> createState() => _CreateApartmentState();

}


class _CreateApartmentState extends State<CreateApartment> {

  bool _nextStep = true;

  Map<String, dynamic> _params = {
    "name": "",
    "phonenumber": "",
    "address": "",
    "regionCode": ""
  };
  int _memberId = 1;
  
  // 省市区数据
  List<dynamic> _provinces = [];
  List<dynamic> _cities = [];
  List<dynamic> _districts = [];
  
  // 选中的省市区
  String _selectedProvince = "";
  String _selectedCity = "";
  String _selectedDistrict = "";
  
  // 省市区名称
  String _provinceName = "";
  String _cityName = "";
  String _districtName = "";
  
  // 加载状态
  bool _loadingCities = false;
  bool _loadingDistricts = false;

  @override
  void initState() {
    super.initState();
    _loadProvinces();
  }
  
  // 加载省份数据
  Future<void> _loadProvinces() async {
    try {
      Map resData = await commonApi.getRegionLazyTree("00");
      if (resData["code"] == 200) {
        setState(() {
          _provinces = resData["data"] ?? [];
          
          // 默认选中第一个省份
          if (_provinces.isNotEmpty) {
            _selectedProvince = _provinces[0]["value"];
            _provinceName = _provinces[0]["title"];
            _loadCities(_selectedProvince);
          }
        });
      }
    } catch (e) {
      print("加载省份数据失败: $e");
    }
  }
  
  // 加载城市数据
  Future<void> _loadCities(String parentCode) async {
    if (_loadingCities) return;
    
    setState(() {
      _loadingCities = true;
    });
    
    try {
      Map resData = await commonApi.getRegionLazyTree(parentCode);
      if (resData["code"] == 200) {
        setState(() {
          _cities = resData["data"] ?? [];
          _loadingCities = false;
          
          // 默认选中第一个城市
          if (_cities.isNotEmpty) {
            _selectedCity = _cities[0]["value"];
            _cityName = _cities[0]["title"];
            _loadDistricts(_selectedCity);
          } else {
            _districts = [];
            _selectedDistrict = "";
            _districtName = "";
          }
        });
      }
    } catch (e) {
      setState(() {
        _loadingCities = false;
      });
      print("加载城市数据失败: $e");
    }
  }
  
  // 加载区县数据
  Future<void> _loadDistricts(String parentCode) async {
    if (_loadingDistricts) return;
    
    setState(() {
      _loadingDistricts = true;
    });
    
    try {
      Map resData = await commonApi.getRegionLazyTree(parentCode);
      if (resData["code"] == 200) {
        setState(() {
          _districts = resData["data"] ?? [];
          _loadingDistricts = false;
          
          // 默认选中第一个区县
          if (_districts.isNotEmpty) {
            _selectedDistrict = _districts[0]["value"];
            _districtName = _districts[0]["title"];
            _params["regionCode"] = _selectedDistrict;
          } else {
            _selectedDistrict = "";
            _districtName = "";
            _params["regionCode"] = "";
          }
        });
      }
    } catch (e) {
      setState(() {
        _loadingDistricts = false;
      });
      print("加载区县数据失败: $e");
    }
  }
  
  // 选择省市区
  void _selectRegion(BuildContext context) {
    if (_provinces.isEmpty) {
      _showErrorDialog("暂无省份数据，请稍后再试");
      return;
    }
    
    // 临时保存选择的值，确认后再更新到state
    String tempProvince = _selectedProvince;
    String tempCity = _selectedCity;
    String tempDistrict = _selectedDistrict;
    String tempProvinceName = _provinceName;
    String tempCityName = _cityName;
    String tempDistrictName = _districtName;
    
    // 临时存储弹窗中的数据
    List<dynamic> tempCities = [..._cities];
    List<dynamic> tempDistricts = [..._districts];
    bool tempLoadingCities = false;
    bool tempLoadingDistricts = false;
    
    // 防抖定时器
    Timer? _provinceDebounce;
    Timer? _cityDebounce;
    
    // 创建滚动控制器
    final ScrollController provinceScrollController = ScrollController();
    final ScrollController cityScrollController = ScrollController();
    final ScrollController districtScrollController = ScrollController();
    
    // 滚动到选中项
    void scrollToSelectedItem(ScrollController controller, int index) {
      if (controller.hasClients) {
        final itemHeight = 56.0; // 假设每个ListTile高度为56
        final screenHeight = MediaQuery.of(context).size.height * 0.5 - 50; // 减去标题栏高度
        final middlePosition = (screenHeight - itemHeight) / 2;
        final scrollTo = index * itemHeight - middlePosition;
        
        controller.animateTo(
          scrollTo < 0 ? 0 : scrollTo,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      } else {
        // 如果控制器还没有附加到滚动视图，延迟执行
        Future.delayed(Duration(milliseconds: 100), () {
          scrollToSelectedItem(controller, index);
        });
      }
    }
    
    // 查找选中项的索引
    int findSelectedIndex(List<dynamic> items, String value) {
      for (int i = 0; i < items.length; i++) {
        if (items[i]["value"] == value) {
          return i;
        }
      }
      return 0;
    }
    
    // 声明函数引用
    Future<void> Function(String, StateSetter) loadCitiesInModal = (_, __) async {};
    Future<void> Function(String, StateSetter) loadDistrictsInModal = (_, __) async {};
    
    // 加载区县数据（弹窗内使用）
    Future<void> _loadDistrictsInModal(String parentCode, StateSetter setModalState) async {
      if (tempLoadingDistricts) return;
      
      setModalState(() {
        tempLoadingDistricts = true;
        tempDistricts = [];
      });
      
      try {
        Map resData = await commonApi.getRegionLazyTree(parentCode);
        if (resData["code"] == 200) {
          setModalState(() {
            tempDistricts = resData["data"] ?? [];
            
            tempLoadingDistricts = false;
            
            // 默认选中第一个区县
            if (tempDistricts.isNotEmpty) {
              tempDistrict = tempDistricts[0]["value"];
              tempDistrictName = tempDistricts[0]["title"];
              
              // 滚动到选中项
              Future.microtask(() {
                scrollToSelectedItem(districtScrollController, 0);
              });
            }
          });
        }
      } catch (e) {
        setModalState(() {
          tempLoadingDistricts = false;
        });
        print("加载区县数据失败: $e");
      }
    }
    
    // 加载城市数据（弹窗内使用）
    Future<void> _loadCitiesInModal(String parentCode, StateSetter setModalState) async {
      if (tempLoadingCities) return;
      
      setModalState(() {
        tempLoadingCities = true;
        tempCities = [];
      });
      
      try {
        Map resData = await commonApi.getRegionLazyTree(parentCode);
        if (resData["code"] == 200) {
          setModalState(() {
            tempCities = resData["data"] ?? [];
            tempLoadingCities = false;
            
            // 清空区县数据
            tempDistricts = [];
            tempDistrict = "";
            tempDistrictName = "";
            
            // 默认选中第一个城市
            if (tempCities.isNotEmpty) {
              tempCity = tempCities[0]["value"];
              tempCityName = tempCities[0]["title"];
              
              // 滚动到选中项
              Future.microtask(() {
                scrollToSelectedItem(cityScrollController, 0);
              });
              
              // 加载区县数据
              loadDistrictsInModal(tempCity, setModalState);
            }
          });
        }
      } catch (e) {
        setModalState(() {
          tempLoadingCities = false;
        });
        print("加载城市数据失败: $e");
      }
    }
    
    // 初始化函数引用
    loadDistrictsInModal = _loadDistrictsInModal;
    loadCitiesInModal = _loadCitiesInModal;
    
    // 防抖函数 - 省份选择
    void _debounceProvinceSelection(String provinceValue, StateSetter setModalState) {
      if (_provinceDebounce?.isActive ?? false) {
        _provinceDebounce!.cancel();
      }
      
      _provinceDebounce = Timer(Duration(milliseconds: 300), () {
        // 只有当省份值发生变化时才加载城市数据
        if (tempProvince != provinceValue) {
          final province = _provinces.firstWhere(
            (p) => p["value"] == provinceValue,
            orElse: () => {"value": provinceValue, "title": ""},
          );
          
          setModalState(() {
            tempProvince = provinceValue;
            tempProvinceName = province["title"];
            tempCity = "";
            tempCityName = "";
            tempDistrict = "";
            tempDistrictName = "";
          });
          
          // 加载城市数据
          loadCitiesInModal(provinceValue, setModalState);
        }
      });
    }
    
    // 防抖函数 - 城市选择
    void _debounceCitySelection(String cityValue, StateSetter setModalState) {
      if (_cityDebounce?.isActive ?? false) {
        _cityDebounce!.cancel();
      }
      
      _cityDebounce = Timer(Duration(milliseconds: 300), () {
        // 只有当城市值发生变化时才加载区县数据
        if (tempCity != cityValue) {
          final city = tempCities.firstWhere(
            (c) => c["value"] == cityValue,
            orElse: () => {"value": cityValue, "title": ""},
          );
          
          setModalState(() {
            tempCity = cityValue;
            tempCityName = city["title"];
            tempDistrict = "";
            tempDistrictName = "";
          });
          
          // 加载区县数据
          loadDistrictsInModal(cityValue, setModalState);
        }
      });
    }
    
    // 初始化数据
    void initModalData(StateSetter setModalState) {
      // 如果已经选择了省份，则加载对应的城市数据
      if (tempProvince.isNotEmpty) {
        // 滚动到选中的省份
        int provinceIndex = findSelectedIndex(_provinces, tempProvince);
        Future.microtask(() {
          scrollToSelectedItem(provinceScrollController, provinceIndex);
        });
        
        // 如果已经有城市数据，则滚动到选中的城市
        if (tempCities.isNotEmpty && tempCity.isNotEmpty) {
          int cityIndex = findSelectedIndex(tempCities, tempCity);
          Future.microtask(() {
            scrollToSelectedItem(cityScrollController, cityIndex);
          });
          
          // 如果已经有区县数据，则滚动到选中的区县
          if (tempDistricts.isNotEmpty && tempDistrict.isNotEmpty) {
            int districtIndex = findSelectedIndex(tempDistricts, tempDistrict);
            Future.microtask(() {
              scrollToSelectedItem(districtScrollController, districtIndex);
            });
          }
        } else {
          // 加载城市数据
          loadCitiesInModal(tempProvince, setModalState);
        }
      }
    }
    
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许占据更多空间
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setModalState) {
            // 初始化数据，确保只执行一次
            Future.microtask(() => initModalData(setModalState));
            
            return Container(
              height: MediaQuery.of(context).size.height * 0.5,
              child: Column(
                children: [
                  Container(
                    height: 50,
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(color: ThemeVars.colorBorder, width: 1),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("选择省市区", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                        TextButton(
                          onPressed: () {
                            // 取消所有防抖定时器
                            _provinceDebounce?.cancel();
                            _cityDebounce?.cancel();
                            
                            // 确认选择，更新state
                            setState(() {
                              _selectedProvince = tempProvince;
                              _selectedCity = tempCity;
                              _selectedDistrict = tempDistrict;
                              _provinceName = tempProvinceName;
                              _cityName = tempCityName;
                              _districtName = tempDistrictName;
                              _cities = tempCities;
                              _districts = tempDistricts;
                              _params["regionCode"] = _selectedDistrict;
                            });
                            Navigator.pop(context);
                          },
                          child: Text("确定"),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Row(
                      children: [
                        // 省份列表
                        Expanded(
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border(
                                right: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                              ),
                            ),
                            child: Stack(
                              children: [
                                // 中间高亮区域
                                Positioned(
                                  left: 0,
                                  right: 0,
                                  top: (MediaQuery.of(context).size.height * 0.5 - 50 - 56) / 2,
                                  height: 56,
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: ThemeVars.colorPrimaryLight.withOpacity(0.3),
                                      border: Border(
                                        top: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                                        bottom: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                                      ),
                                    ),
                                  ),
                                ),
                                // 列表
                                ListWheelScrollView.useDelegate(
                                  controller: FixedExtentScrollController(
                                    initialItem: findSelectedIndex(_provinces, tempProvince),
                                  ),
                                  itemExtent: 56, // 每项高度
                                  perspective: 0.005, // 透视效果
                                  diameterRatio: 1.5, // 直径比例
                                  physics: FixedExtentScrollPhysics(),
                                  onSelectedItemChanged: (index) {
                                    final province = _provinces[index];
                                    // 使用防抖函数
                                    _debounceProvinceSelection(province["value"], setModalState);
                                  },
                                  childDelegate: ListWheelChildBuilderDelegate(
                                    childCount: _provinces.length,
                                    builder: (context, index) {
                                      final province = _provinces[index];
                                      final isSelected = tempProvince == province["value"];
                                      return Container(
                                        alignment: Alignment.center,
                                        child: Text(
                                          province["title"],
                                          style: TextStyle(
                                            color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorText,
                                            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                            fontSize: isSelected ? 16 : 14,
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        // 城市列表
                        Expanded(
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border(
                                right: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                              ),
                            ),
                            child: tempLoadingCities
                                ? Center(child: CircularProgressIndicator())
                                : Stack(
                                    children: [
                                      // 中间高亮区域
                                      Positioned(
                                        left: 0,
                                        right: 0,
                                        top: (MediaQuery.of(context).size.height * 0.5 - 50 - 56) / 2,
                                        height: 56,
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color: ThemeVars.colorPrimaryLight.withOpacity(0.3),
                                            border: Border(
                                              top: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                                              bottom: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                                            ),
                                          ),
                                        ),
                                      ),
                                      // 列表
                                      ListWheelScrollView.useDelegate(
                                        controller: FixedExtentScrollController(
                                          initialItem: tempCities.isNotEmpty ? findSelectedIndex(tempCities, tempCity) : 0,
                                        ),
                                        itemExtent: 56, // 每项高度
                                        perspective: 0.005, // 透视效果
                                        diameterRatio: 1.5, // 直径比例
                                        physics: FixedExtentScrollPhysics(),
                                        onSelectedItemChanged: (index) {
                                          if (tempCities.isEmpty || index >= tempCities.length) return;
                                          final city = tempCities[index];
                                          // 使用防抖函数
                                          _debounceCitySelection(city["value"], setModalState);
                                        },
                                        childDelegate: ListWheelChildBuilderDelegate(
                                          childCount: tempCities.length,
                                          builder: (context, index) {
                                            final city = tempCities[index];
                                            final isSelected = tempCity == city["value"];
                                            return Container(
                                              alignment: Alignment.center,
                                              child: Text(
                                                city["title"],
                                                style: TextStyle(
                                                  color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorText,
                                                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                                  fontSize: isSelected ? 16 : 14,
                                                ),
                                              ),
                                            );
                                          },
                                        ),
                                      ),
                                    ],
                                  ),
                          ),
                        ),
                        // 区县列表
                        Expanded(
                          child: tempLoadingDistricts
                              ? Center(child: CircularProgressIndicator())
                              : Stack(
                                  children: [
                                    // 中间高亮区域
                                    Positioned(
                                      left: 0,
                                      right: 0,
                                      top: (MediaQuery.of(context).size.height * 0.5 - 50 - 56) / 2,
                                      height: 56,
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: ThemeVars.colorPrimaryLight.withOpacity(0.3),
                                          border: Border(
                                            top: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                                            bottom: BorderSide(color: ThemeVars.colorBorder, width: 0.5),
                                          ),
                                        ),
                                      ),
                                    ),
                                    // 列表
                                    ListWheelScrollView.useDelegate(
                                      controller: FixedExtentScrollController(
                                        initialItem: tempDistricts.isNotEmpty ? findSelectedIndex(tempDistricts, tempDistrict) : 0,
                                      ),
                                      itemExtent: 56, // 每项高度
                                      perspective: 0.005, // 透视效果
                                      diameterRatio: 1.5, // 直径比例
                                      physics: FixedExtentScrollPhysics(),
                                      onSelectedItemChanged: (index) {
                                        if (tempDistricts.isEmpty || index >= tempDistricts.length) return;
                                        final district = tempDistricts[index];
                                        setModalState(() {
                                          tempDistrict = district["value"];
                                          tempDistrictName = district["title"];
                                        });
                                      },
                                      childDelegate: ListWheelChildBuilderDelegate(
                                        childCount: tempDistricts.length,
                                        builder: (context, index) {
                                          final district = tempDistricts[index];
                                          final isSelected = tempDistrict == district["value"];
                                          return Container(
                                            alignment: Alignment.center,
                                            child: Text(
                                              district["title"],
                                              style: TextStyle(
                                                color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorText,
                                                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                                fontSize: isSelected ? 16 : 14,
                                              ),
                                            ),
                                          );
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
  
  // 显示错误提示对话框
  void _showErrorDialog(String message) {
    EasyLoading.showToast(message);
  }

  bool _validate() {
    if (_params["name"] == null || _params["name"] == "") {
      _showErrorDialog("请输入公寓名称");
      return false;
    }
    if (_params["phonenumber"] == null || _params["phonenumber"].length != 11) {
      _showErrorDialog("请输入正确的客服电话");
      return false;
    }
    if (_params["regionCode"] == null || _params["regionCode"] == "") {
      _showErrorDialog("请选择省市区");
      return false;
    }
    if (_params["address"] == null || _params["address"] == "") {
      _showErrorDialog("请输入公寓详细地址");
      return false;
    }
    return true;
  }

  void _createApartment(commonVM) async {
    if (!_validate()) return;
    
    Map<String, dynamic> params = {
      ..._params,
    };
    await apartmentApi.createApartment(params);
    await _getApartmentInfo(commonVM);
    EasyLoading.showSuccess("创建成功");
    Stacker.pushAndRemoveUntil(const TransferStation());
  }

  Future<void> _getApartmentInfo(commonVM) async {
    Map resData = await apartmentApi.getApartmentInfo();
    if (context.mounted) {
      print("apartInfo :>>> ${resData["data"]}");
      commonVM.setApartment(resData["data"]);
      storage.setString("apartment", jsonEncode(resData["data"]));
    }
  }

  Future<void> _logout(BuildContext context) async {
    await userApi.logout();
    storage.remove("token");
    storage.remove("apartment");
    storage.remove("info");
    Stacker.pushAndRemoveUntil(const TransferStation());
  }

  void _handleBack() {
    // 检查当前路由是否是从登录页面直接进入的
    final token = storage.getString("token") ?? "";
    final apartment = storage.getString("apartment") ?? "";
    
    // 如果有token但没有apartment，说明是从登录页直接进入的
    if (token.isNotEmpty && apartment.isEmpty) {
      _logout(context);
    } else {
      Navigator.pop(context);
    }
  }

  Widget _render() {
    if (_nextStep) {
      return Container(
          padding: EdgeInsets.all(ThemeVars.paddingPage),
          height: MediaQuery.of(context).size.height,
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("目前不属于任何公寓，可创建公寓或与公寓管理员联系", style: TextStyle(color: ThemeVars.colorTextSec), textAlign: TextAlign.center,),
                SizedBox(height: 30,),
                Button(
                  type: ButtonType.primary,
                  onPressed: () {
                    setState(() {
                      _nextStep = false;
                    });
                  },
                  child: Text("创建公寓"),
                )
              ],
            ),
          )
      );
    } else {
      return Consumer<CommonState>(builder: (ctx, commonVM, child) {
        return ListView(
          children: [
            MenuBlock(
              items: [
                MenuBlockItem(
                  text: "公寓名称",
                  showArrow: false,
                  suffix: TextFormField(
                    textAlign: TextAlign.right,
                    decoration: const InputDecoration(
                      hintText: "请输入",
                      hintStyle: TextStyle(color: ThemeVars.colorTextTer),
                      border: InputBorder.none,
                      isDense: true,
                    ),
                    initialValue: _params["name"],
                    onChanged: (val) {
                      setState(() {
                        _params["name"] = val;
                      });
                    },
                  ),
                ),
                MenuBlockItem(
                  text: "客服电话",
                  showArrow: false,
                  suffix: TextFormField(
                    textAlign: TextAlign.right,
                    decoration: const InputDecoration(
                      hintText: "请输入",
                      hintStyle: TextStyle(color: ThemeVars.colorTextTer),
                      border: InputBorder.none,
                      isDense: true,
                    ),
                    initialValue: _params["phonenumber"],
                    onChanged: (val) {
                      setState(() {
                        _params["phonenumber"] = val;
                      });
                    },
                  ),
                ),
                MenuBlockItem(
                  text: "所在省市区",
                  showArrow: true,
                  onTap: () => _selectRegion(context),
                  suffix: Text(
                    _selectedProvince.isEmpty ? "请选择" : 
                    "$_provinceName $_cityName $_districtName",
                    style: TextStyle(
                      color: _selectedProvince.isEmpty ? ThemeVars.colorTextTer : ThemeVars.colorText,
                    ),
                  ),
                ),
                MenuBlockItem(
                  text: "详细地址",
                  showArrow: false,
                  suffix: TextFormField(
                    textAlign: TextAlign.right,
                    decoration: const InputDecoration(
                      hintText: "请输入",
                      hintStyle: TextStyle(color: ThemeVars.colorTextTer),
                      border: InputBorder.none,
                      isDense: true,
                    ),
                    initialValue: _params["address"],
                    onChanged: (val) {
                      setState(() {
                        _params["address"] = val;
                      });
                    },
                  ),
                )
              ],
            ),
            SizedBox(height: 30,),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
              child: Button(
                type: ButtonType.primary,
                onPressed: () {
                  _createApartment(commonVM);
                },
                child: Text("创建公寓"),
              ),
            )
          ],
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "创建公寓",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios),
        onPressed: _handleBack,
      ),
      child: _render(),
    );
  }

}